package com.sunhao.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunhao.common.utils.HttpUtils;
import com.sunhao.gulimall.member.dao.MemberLevelDao;
import com.sunhao.gulimall.member.entity.MemberLevelEntity;
import com.sunhao.gulimall.member.exception.PhoneExistException;
import com.sunhao.gulimall.member.exception.UserNameExistException;
import com.sunhao.gulimall.member.vo.MemberLoginVo;
import com.sunhao.gulimall.member.vo.MemberRegisterVo;
import com.sunhao.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunhao.common.utils.PageUtils;
import com.sunhao.common.utils.Query;

import com.sunhao.gulimall.member.dao.MemberDao;
import com.sunhao.gulimall.member.entity.MemberEntity;
import com.sunhao.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity member = new MemberEntity();
        MemberLevelEntity level = memberLevelDao.getDefaultLevel();

        if (level != null)
        {
            member.setLevelId(level.getId());
        }


        //检查用户名和手机号唯一性
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        member.setUsername(vo.getUserName());
        member.setMobile(vo.getPhone());

        //设置密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        member.setPassword(encode);

        this.baseMapper.insert(member);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0)
            throw new PhoneExistException();
    }

    @Override
    public void checkUserNameUnique(String username) throws UserNameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0)
            throw new UserNameExistException();
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        MemberEntity member = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (member == null)
        {
            return null;
        }
        else
        {
            String passwordDB = member.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, passwordDB);
            if (matches)
                return member;
            else
                return null;
        }
    }

    /**
     * 第三方登录 登录和注册合并逻辑
     * @param socialUser 微博授权后获取的token uid等信息
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();

        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null)
        {
            MemberEntity update = new MemberEntity();

            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

            return memberEntity;
        }
        else {
            MemberEntity register = new MemberEntity();
            //获取的信息相对不重要，真正重要的是uid
           try {
               Map<String,String> query = new HashMap<>();
               query.put("access_token",socialUser.getAccess_token());
               query.put("uid",socialUser.getUid());
               HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

               if (response.getStatusLine().getStatusCode()==200)
               {
                   String json = EntityUtils.toString(response.getEntity());
                   JSONObject object = JSON.parseObject(json);
                   String name = object.getString("name");
                   String gender = object.getString("gender");

                   register.setNickname(name);
                   register.setGender("m".equals(gender)?1:0);
               }
           }catch (Exception e){}
           register.setSocialUid(socialUser.getUid());
           register.setAccessToken(socialUser.getAccess_token());
           register.setExpiresIn(String.valueOf(socialUser.getExpires_in()));

           this.baseMapper.insert(register);

           return register;
        }
    }

}